package demo2;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-06
 * Time: 8:26
 */
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}
class Solution {
    public Node connect(Node root) {
        if (root == null)
            return root;
        Node head = root;
        while(head!=null){
            Node dummy = new Node(-1);
            Node temp = dummy;
            while(head!=null){
                if (head.left!= null){
                    temp.next= head.left;
                    temp= temp.next;
                }
                if (head.right!= null){
                    temp.next = head.right;
                    temp = temp.next;
                }
                head = head.next;
            }
            head = dummy.next;
        }
        return root;
    }
}
class Solution1 {
    public Node connect(Node root) {
        if (root == null) return null;
        if (root.left != null) { // update left next
            if (root.right != null) {
                // if right child exists - simple connect left.next to right
                root.left.next = root.right;
            }
            else {
                // if not - scan parent next node until we find the first left or right child
                root.left.next = findNext(root);
            }
        }
        if (root.right != null) { // update right next
            root.right.next = findNext(root);
        }

        connect(root.right); // update the right nodes first
        connect(root.left);
        return root;
    }

    private Node findNext(Node root) { // get parent node
        while (root.next != null) { // scan all next parent nodes until we find the first left or right child
            root = root.next;
            if (root.left != null) return root.left;
            if (root.right != null) return root.right;
        }
        return null;
    }
}

public class TestDemo {
}
